package com.o2opuzi.lib.db;

import org.springframework.util.StringUtils;


/**
 * 类型转换
 * @author yue
 * @date 2014-9-3
 */
public class Converter {
	
	
	/**
	 * 类型转换
	 * @auther Y.hj
	 * @param type
	 * @param value
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T convert(Class<T> type,String value){
		Object result = null;
		try {
			if(StringUtils.isEmpty(value))
				result = value;
			if(type.equals(String.class))
				result =  value;
			else if (type.equals(Integer.class) || type.equals(int.class))
				result = Integer.parseInt(value);
			else if(type.equals(Long.class) || type.equals(long.class))
				result = Long.parseLong(value);
			else if(type.equals(Double.class) || type.equals(double.class))
				result = Double.parseDouble(value);
			else if(type.equals(Short.class) || type.equals(short.class))
				result = Short.parseShort(value);
			else if(type.equals(Byte.class) || type.equals(byte.class))
				result = Byte.parseByte(value);
			else if(type.equals(Boolean.class) || type.equals(boolean.class)){
				if(value.equals("true") || value.equals("1") || value.equals("on"))
					result = true;
				if(value.equals("false") || value.equals("0") || value.equals("off"))
					result = false;
			}
		} catch (Exception e) {
			new RuntimeException(e);
		}
		return (T) result;
	}
	
	/**
	 * 类型转换
	 * @auther Y.hj
	 * @param type
	 * @param valueArray
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T converter(Class<T> type,String[] valueArray){
		Object result = null;
		if(type.equals(String[].class))
			result = valueArray;
		else if(type.equals(Integer[].class) || type.equals(int[].class)){
			int[] values = new int[valueArray.length];
			for (int i = 0; i < values.length; i++)
				values[i] = convert(int.class, valueArray[i]);
			result = values;
		}
		else if(type.equals(Long[].class) || type.equals(long[].class)){
			long[] values = new long[valueArray.length];
			for (int i = 0; i < values.length; i++)
				values[i] = convert(long.class, valueArray[i]);
			result = values;
		}
		else if(type.equals(Long[].class) || type.equals(double[].class)){
			double[] values = new double[valueArray.length];
			for (int i = 0; i < values.length; i++)
				values[i] = convert(double.class, valueArray[i]);
			result = values;
		}
		if(type.equals(Short[].class) || type.equals(short[].class)){
			short[] values = new short[valueArray.length];
			for (int i = 0; i < values.length; i++)
				values[i] = convert(short.class, valueArray[i]);
			result = values;
		}
		else if(type.equals(Boolean[].class) || type.equals(boolean[].class)){
			boolean[] values = new boolean[valueArray.length];
			for (int i = 0; i < values.length; i++)
				values[i] = convert(boolean.class, valueArray[i]);
			result = values;
		}
		return (T) result;
	}
}
